namespace RBAC.Read.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.QualityCommand;
    using RBAC.Read.Api.Application.Dto.Quality;
    using System.Linq;

    /// <summary>
    /// 按质量工单 Id 获取附件列表 处理器。
    /// </summary>
    /// <remarks>
    /// 主要逻辑：
    /// 1. 校验 <c>OrderId</c> > 0。
    /// 2. 查询未删除（<c>IsDeleted = 0</c>）的附件集合。
    /// 3. 映射为 <see cref="QualityOrderAttachmentDto"/> 列表返回。
    /// 4. 统一取消与异常处理。
    /// </remarks>
    /// </summary>
    public class GetQualityOrderAttachmentListByOrderIdHandler : IRequestHandler<GetQualityOrderAttachmentListByOrderIdCommand, APIResult<List<QualityOrderAttachmentDto>>>
    {
        private readonly IBaseRepository<QualityOrderAttachment> _attRepo;
        private readonly ILogger<GetQualityOrderAttachmentListByOrderIdHandler> _logger;

        public GetQualityOrderAttachmentListByOrderIdHandler(IBaseRepository<QualityOrderAttachment> attRepo, ILogger<GetQualityOrderAttachmentListByOrderIdHandler> logger)
        {
            _attRepo = attRepo;
            _logger = logger;
        }
         
        /// <summary>
        /// 处理“按工单 Id 获取附件列表”请求。
        /// </summary>
        /// <param name="request">包含工单 Id 的查询命令。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回 <see cref="APIResult{T}"/>，<c>Data</c> 为附件列表。</returns>
        public Task<APIResult<List<QualityOrderAttachmentDto>>> Handle(GetQualityOrderAttachmentListByOrderIdCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<QualityOrderAttachmentDto>>();
            try
            {
                // 检查是否被取消
                cancellationToken.ThrowIfCancellationRequested();
                // 参数校验：OrderId 必须有效
                if (request.OrderId <= 0)
                {
                    return Task.FromResult(new APIResult<List<QualityOrderAttachmentDto>> { Code = APIEnums.Fail, Msg = "OrderId无效", Data = new List<QualityOrderAttachmentDto>() });
                }

                // 仓储：获取未删除的附件列表 
                var list = _attRepo.GetAll("QualityOrderId = @OrderId AND IsDeleted = 0", new { OrderId = request.OrderId })
                    .Select(a => new QualityOrderAttachmentDto
                    {
                        Id = a.Id,
                        QualityOrderId = a.QualityOrderId,
                        FileName = a.FileName,
                        FileUrl = a.FileUrl,
                        FileSize = a.FileSize,
                        ContentType = a.ContentType,
                        FileHash = a.FileHash,
                        UploadTime = a.UploadTime,
                        Status = a.Status,
                        Remark = a.Remark
                    }).ToList();

                // 设置返回结果
                result.Code = APIEnums.Success;
                result.Data = list;
                result.Msg = "获取附件列表成功";
            }
            catch (OperationCanceledException)
            {
                // 捕获取消异常
                _logger.LogWarning("获取附件列表被取消");
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.Data = new List<QualityOrderAttachmentDto>();
            }
            catch (Exception ex)
            {
                // 统一异常处理与日志
                _logger.LogError(ex, "获取附件列表失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取附件列表失败";
                result.Data = new List<QualityOrderAttachmentDto>();
            }

            return Task.FromResult(result);
        }
    }
}
